<template>
  <view class="container">
    <view class="profile-container">
      <!-- 用户信息区域 -->
      <view class="user-info">
        <image
          class="background-image"
          src="https://jht.jingang.icu/img/minebg.jpg"
          mode="aspectFill"
        ></image>
        <view class="user-info-content">
          <image
            class="avatar"
            :src="userData.avatar || 'https://jht.jingang.icu/img/my.png'"
            mode="aspectFill"
            @error="handleAvatarError"
          ></image>
          <view class="user-details">
            <view class="username-row">
              <text class="username">{{ userData.nickname || "未登录" }}</text>
              <text class="user-score" v-if="userData.score !== null">
                <image
                  src="https://jht.jingang.icu/img/img17410018acb75e5c0.png"
                  mode="scaleToFill"
                />
                当前积分：{{ userData.score }}</text
              >
              <uni-icons
                class="arrow-icon"
                type="arrowright"
                size="14"
                color="#546AAC"
              ></uni-icons>
            </view>
            <text class="user-intr">{{ userData.intr || "暂无个人简介" }}</text>
          </view>
        </view>

        <view class="settings-icon">
          <uni-icons type="gear" size="24" color="#fff"></uni-icons>
        </view>
      </view>

      <view class="user-info-actions">
        <view class="stats-container">
          <view class="stat-item">
            <text class="stat-number">{{ userData.starCount || 0 }}</text>
            <text class="stat-label">商品收藏</text>
          </view>
          <view class="divider"></view>
          <view class="stat-item">
            <text class="stat-number">{{ userData.spoorCount || 0 }}</text>
            <text class="stat-label">浏览足迹</text>
          </view>
          <view class="divider"></view>
          <view class="stat-item">
            <text class="stat-number">{{ userData.couponCount || 0 }}</text>
            <text class="stat-label">优惠券</text>
          </view>
        </view>
      </view>

      <!-- 新增功能行 -->
      <view class="new-functions">
        <view class="function-block" @click="goToScore">
          <view class="function-icon score-icon">
            <image
              src="https://jht.jingang.icu/img/img17374918acb4851c8.png"
              mode="scaleToFill"
            />
          </view>
          <text class="function-text">积分管理</text>
        </view>

        <view class="function-block" @click="clearCacheAndLogout">
          <view class="function-icon cache-icon">
            <image
              src="https://jht.jingang.icu/img/img17375218acb487108.png"
              mode="scaleToFill"
            />
          </view>
          <text class="function-text">清除缓存</text>
        </view>

        <view class="function-block" @click="goToAddress">
          <view class="function-icon address-icon">
            <image
              src="https://jht.jingang.icu/img/img17375518acb48b758.png"
              mode="scaleToFill"
            />
          </view>
          <text class="function-text">收货地址</text>
        </view>

        <view class="function-block" @click="goToClockIn">
          <view class="function-icon clockin-icon">
            <image
              src="https://jht.jingang.icu/img/img17436218acb9f3fb0.png"
              mode="scaleToFill"
            />
          </view>
          <text class="function-text">打卡</text>
        </view>

        <view
          class="function-block"
          @click="goToStudentManage"
          v-if="userData.role == 2"
        >
          <view class="function-icon student-icon">
            <image
              src="https://jht.jingang.icu/img/img17375718acb48f5d8.png"
              mode="scaleToFill"
            />
          </view>
          <text class="function-text">学员管理</text>
        </view>
      </view>

      <!-- 订单状态 -->
      <view
        class="section-title"
        style="justify-content: space-between; margin-top: 20%"
      >
        <text>我的订单</text>
        <view class="more-orders" @click="goToAllOrders">
          <text>查看全部订单</text>
          <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <view class="order-status">
        <view class="status-item" @click="goToOrders(1)">
          <image
            src="https://jht.jingang.icu/img/img17400418acb6a06b0.png"
            mode="scaleToFill"
          />
          <text class="status-text">待付款</text>
        </view>
        <view class="status-item" @click="goToOrders(2)">
          <image
            src="https://jht.jingang.icu/img/img17400718acb6a3d60.png"
            mode="scaleToFill"
          />
          <text class="status-text">待发货</text>
        </view>
        <view class="status-item" @click="goToOrders(3)">
          <image
            src="https://jht.jingang.icu/img/img17401018acb6a6c40.png"
            mode="scaleToFill"
          />
          <text class="status-text">待收货</text>
        </view>
        <view class="status-item" @click="goToOrders(4)">
          <image
            src="https://jht.jingang.icu/img/img17401118acb6a9738.png"
            mode="scaleToFill"
          />
          <text class="status-text">待评价</text>
        </view>
      </view>

      <!-- 活动 -->
      <view class="action">
        <image
          src="https://jht.jingang.icu/img/action.png"
          mode="scaleToFill"
        />
      </view>

      <!-- 猜你喜欢 -->
      <view class="section-title" style="background-color: inherit">
        <image
          src="https://jht.jingang.icu/img/img17184318ac6cab8e8.png"
          mode="scaleToFill"
        />
        <text>猜你喜欢</text>
      </view>

      <view class="goods-waterfall">
        <view
          class="goods-item"
          v-for="(item, index) in favoriteGoods"
          :key="index"
          @click="goToProduct(item.id)"
        >
          <image
            class="goods-image"
            :src="item.img || 'https://jht.jingang.icu/img/default_goods.png'"
            mode="aspectFill"
          ></image>
          <view class="goods-info">
            <text class="goods-title">{{ item.title || "商品名称" }}</text>
            <text class="goods-synopsis">{{
              item.synopsis || item.title || "商品描述"
            }}</text>
            <view class="goods-footer">
              <text class="goods-price">¥{{ item.price || 0 }}</text>
              <text
                class="goods-original-price"
                v-if="item.original_price && item.original_price != item.price"
                >¥{{ item.original_price }}</text
              >
              <text class="goods-sold">已售{{ item.sold || 0 }}件</text>
            </view>
          </view>
        </view>
        <view v-if="favoriteGoods.length === 0" class="no-data">
          <text>暂无推荐商品</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { userApi } from '@/api/indexAPI.js';

export default {
  components: {
    uniIcons,
  },
  data() {
    return {
      userData: {
        avatar: "",
        nickname: "",
        intr: "",
        score: 0,
        starCount: 0,
        spoorCount: 0,
        couponCount: 0,
        gender: "",
        birthday: "",
        audits: "",
        username: "",
        role: "",
      },
      favoriteGoods: [],
    };
  },
  onLoad() {
    // 页面加载时加载用户数据
    console.log("页面加载，开始获取用户数据");
    this.loadCenterData();
  },
  onShow() {
    // 每次显示页面时重新加载用户信息
    console.log("页面显示，重新获取用户数据");
    this.loadCenterData();
  },
  methods: {
    handleAvatarError() {
      // 当头像加载失败时，使用默认头像
      this.userData.avatar = "https://jht.jingang.icu/img/my.png";
    },
    loadCenterData() {
      console.log("======= loadCenterData 函数执行 =======");
      const userinfo = uni.getStorageSync("userinfo");
      console.log("从本地存储获取用户信息:", userinfo);

      // 如果没有用户信息，直接使用默认数据，不请求接口
      if (!userinfo) {
        console.log("本地存储中没有用户信息对象");
        this.loadDefaultData();
        return;
      }

      // 从本地存储中获取用户信息
      const userData = userinfo.data || userinfo.userinfo || userinfo;
      if (userData) {
        this.userData = {
          avatar: userData.avatar || this.defaultAvatar,
          nickname: userData.nickname || "访客",
          intr: userData.intr || "暂无个人简介",
          score: userData.score !== null ? userData.score : 0,
          starCount: userData.starCount || 0,
          spoorCount: userData.spoorCount || 0,
          couponCount: userData.couponCount || 0,
          gender: userData.gender || "",
          birthday: userData.birthday || "",
          audits: userData.audits || "",
          username: userData.username || userData.nickname || "访客",
          role: userData.role !== null ? userData.role : "",
        };
      }

      const userId = userData.id;
      console.log("准备请求用户中心数据，用户ID:", userId);

      if (!userId) {
        console.log("用户ID为空，不发送请求");
        return;
      }

      userApi.getUserCenter({uid: userId})
        .then(res => {
          if (res.code === 1) {
            // 优先使用本地存储的头像和昵称（微信获取的）
            let avatar = this.userData.avatar;
            let nickname = this.userData.nickname;
            
            // 如果本地没有头像但接口有返回，则使用接口返回的
            if ((!avatar || avatar === this.defaultAvatar) && res.data.avatar) {
              avatar = res.data.avatar;
            }
            
            // 如果本地没有昵称但接口有返回，则使用接口返回的
            if ((!nickname || nickname === "访客") && res.data.nickname) {
              nickname = res.data.nickname;
            }

            // 更新用户数据
            this.userData = {
              avatar: avatar,
              nickname: nickname,
              intr: res.data.intr || "暂无个人简介",
              score: res.data.score !== null ? res.data.score : 0,
              starCount: res.data.starCount || 0,
              spoorCount: res.data.spoorCount || 0,
              couponCount: res.data.couponCount || 0,
              gender: res.data.gender || "",
              birthday: res.data.birthday || "",
              audits: res.data.audits || "",
              username: res.data.username || nickname || "访客",
              role: res.data.role !== null ? res.data.role : "",
            };

            console.log("处理后的userData:", this.userData);

            // 处理商品列表数据
            if (res.data.list && Array.isArray(res.data.list)) {
              // 格式化商品数据以匹配前端展示需要的字段
              this.favoriteGoods = res.data.list.map((item, index) => {
                return {
                  id: item.id,
                  img:
                    item.img || "https://jht.jingang.icu/img/default_goods.png",
                  title: item.title || "商品标题",
                  synopsis: item.synopsis || item.title || "商品描述",
                  price: item.price || 0,
                  original_price: item.original_price || item.price || 0,
                  sold: item.sold || 0,
                };
              });
            } else {
              this.favoriteGoods = [];
            }
          } else {
            console.log("获取用户中心数据失败:", res);
          }
        })
        .catch(err => {
          console.log("请求用户中心数据失败:", err);
        });
    },

    loadDefaultData() {
      // 加载默认数据
      this.userData = {
        avatar: "",
        nickname: "访客",
        intr: "暂无个人简介",
        score: 0,
        starCount: 0,
        spoorCount: 0,
        couponCount: 0,
        gender: "",
        birthday: "",
        audits: "",
        username: "访客",
        role: "",
      };
      this.favoriteGoods = [];
      console.log("使用默认数据");
    },
    clearCacheAndLogout() {
      uni.showModal({
        title: "提示",
        content: "确定要清除缓存并退出登录吗？",
        success: (res) => {
          if (res.confirm) {
            try {
              // 清除本地存储的所有信息
              uni.clearStorageSync();

              // 跳转到登录页面
              uni.redirectTo({
                url: "/pages/login/login",
              });
            } catch (err) {
              console.error("清除缓存并退出登录失败", err);
              uni.showToast({
                title: "操作失败",
                icon: "none",
              });
            }
          }
        },
      });
    },
    goToAddress() {
      uni.navigateTo({
        url: "/pages/location/location",
      });
    },
    goToOrders(status) {
      uni.navigateTo({
        url: "/pages/order/order?status=" + status,
      });
    },
    goToAllOrders() {
      uni.navigateTo({
        url: "/pages/order/order",
      });
    },
    goToProduct(id) {
      if (id) {
        uni.navigateTo({
          url: "/pages/product/product?id=" + id,
        });
      } else {
        uni.showToast({
          title: "商品信息有误",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.profile-container {
  padding-bottom: 20rpx;
}

.user-info {
  display: flex;
  height: 230px;
  flex-direction: row;
  align-items: center;
  color: #546aac;
  position: relative;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.user-info-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  z-index: 1;
  width: 100%;
  padding-left: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  margin-right: 20rpx;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.username-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10rpx;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  margin-right: 10rpx;
}

.user-score {
  font-size: 24rpx;
  padding: 4rpx 10rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
}

.user-score image {
  width: 20rpx;
  height: 20rpx;
}

.arrow-icon {
  align-self: center;
}

.user-intr {
  font-size: 24rpx;
  opacity: 0.9;
}

.settings-icon {
  position: absolute;
  top: 60rpx;
  right: 30rpx;
  z-index: 2;
}

.new-functions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 30rpx 0;
  position: absolute;
  width: 100%;
  top: 27%;
}

.function-block {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.function-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.function-icon image {
  width: 60rpx;
  height: 60rpx;
}

.function-text {
  font-size: 24rpx;
  color: #666;
}

.section-title {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 30rpx 10rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  background-color: white;
}

.section-title image {
  width: 30rpx;
  height: 30rpx;
}

.more-orders {
  display: flex;
  flex-direction: row;
  align-items: center;
  font-size: 24rpx;
  font-weight: normal;
  color: #999;
}

.order-status {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  background-color: #fff;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-item image {
  width: 50rpx;
  height: 50rpx;
}

.status-text {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

.user-info-actions {
  display: flex;
  justify-content: center;
  width: 100%;
  z-index: 2;
  position: absolute;
  top: 20%;
}

.stats-container {
  display: flex;
  flex-direction: row;
  border-radius: 16rpx;
  padding: 20rpx 0;
  width: 90%;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #000;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #000;
}

.divider {
  width: 2rpx;
  height: 60rpx;
  background-color: #666;
}

/* 活动 */
.action {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  margin-bottom: 20rpx;
  margin-top: 3%;
}
.action image {
  width: 100%;
  height: 150px;
}

.goods-waterfall {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20rpx;
}

.goods-item {
  width: 49%;
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.goods-image {
  width: 100%;
  height: 300rpx;
}

.goods-info {
  padding: 15rpx;
}

.goods-title {
  font-size: 28rpx;
  color: #333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-synopsis {
  font-size: 24rpx;
  color: #999;
  margin: 10rpx 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}
.goods-footer {
	display: flex;
	flex-direction: row;
	align-items: baseline;
	justify-content: space-between;
}

.goods-price-row {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  margin-bottom: 10rpx;
}

.goods-price {
  font-size: 32rpx;
  color: #ff4757;
  font-weight: bold;
  margin-right: 10rpx;
}

.goods-original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.goods-sold {
  font-size: 20rpx;
  color: #999;
}

.no-data {
  width: 100%;
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
